﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using System.IO;
using System.Collections.ObjectModel;
using System.Data;
using VAdvantage.DataBase;
using VAdvantage.Utility;
using System.Collections.Generic;
using VAdvantage.Model;
using System.ComponentModel;
using VAdvantage.Classes;

namespace VAdvantage.WorkSpace
{
    public class LatestSubscribedRecordChat : System.ComponentModel.INotifyPropertyChanged
    {
        public ImageSource UserImg { get; set; }
        public string ChatData { get; set; }
        public string ChatDate { get; set; }
        public string UserName { get; set; }
        public double _chatWidth = 0;
        public double ChatWidth
        {
            get
            {
                return _chatWidth;
            }
            set
            {
                _chatWidth = value;
                OnPropertyChanged("ChatWidth");
            }
        }

        static string _text = null;

        public LatestSubscribedRecordChat()
        {

        }

        public LatestSubscribedRecordChat(MemoryStream memStream, string charData, string chatdate, string userName, double chatwidth)
        {

            if (memStream != null)
            {
                BitmapImage img = new BitmapImage();
                img.SetSource(memStream);
                this.UserImg = img;
            }
            else
            {
                this.UserImg = Envs.LoadImageSource("DefaultProfilePic.png");
            }
            this.ChatData = charData;
            this.ChatDate = chatdate;
            this.UserName = userName;
            if (chatwidth <= 0)
            {
                this.ChatWidth = 354;
            }
            else
            {
                this.ChatWidth = chatwidth;
            }

            //  VAdvantage.WorkSpace.GetChatData get = new GetChatData();
        }


        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
    }

    public class GetChatData : ObservableCollection<LatestSubscribedRecordChat>, System.ComponentModel.INotifyPropertyChanged
    {
        int chatId = 0;
        int tableID = 0;
        int RecordID = 0;
        const int SUBTRACTED_WIDTH = 85;
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
        public GetChatData()
        {
            GetData();

        }

        public void GetData()
        {
            //IsTextVisible = Visibility.Collapsed;
            //IsListVisible = Visibility.Collapsed;
            BusyIndicator = true;
            // IsListVisible = Visibility.Collapsed;
            DataSet ds = null;
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                string sql = "select AD_TABLE_ID,RECORD_ID from CM_Subscribe Where AD_User_ID=" + Envs.GetCtx().GetAD_User_ID();

                ds = DB.ExecuteDataset(sql, null);
                string table_ID = "";
                string rec_ID = "";
                if (ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        table_ID += ds.Tables[0].Rows[i][0].ToString() + ',';
                        rec_ID += ds.Tables[0].Rows[i][1].ToString() + ',';
                    }
                    table_ID = table_ID.Substring(0, table_ID.Length - 1);
                    rec_ID = rec_ID.Substring(0, rec_ID.Length - 1);
                    string sqlQuery = " select * from(select cm.characterdata,cm.CM_Chat_ID,binarydata, cm.created, user1.name,chat.ad_table_id, chat.record_id from cm_chatentry cm JOIN ad_User user1"
           + "       ON (user1.ad_user_id= cm.createdby) left outer join  AD_IMAGE image ON (image.ad_image_id=user1.ad_image_id)  JOIN cm_chat chat on(chat.cm_chat_id=cm.cm_chat_id) WHERE chat.cm_chat_id="
           + "       ( SELECT cm.cm_chat_id FROM cm_chatentry cm JOIN cm_chat chat on(chat.cm_chat_id=cm.cm_chat_id) WHERE cm_chatentry_id = (SELECT MAX(ce.cm_chatentry_id)   FROM CM_Chat chat"
           + "  JOIN ad_User user1 ON (user1.ad_user_id= chat.createdby) JOIN cm_chatentry CE ON(chat.cm_chat_id   = ce.cm_chat_id)  WHERE chat.Ad_Table_ID IN(" + table_ID + ") AND chat.Record_ID IN(" + rec_ID + "))) order by cm.cm_chatentry_id desc) inn where rownum<3 order by rownum desc";
                    ds = new DataSet();
                    ds = DB.ExecuteDataset(sqlQuery, null);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        chatId = Convert.ToInt32(ds.Tables[0].Rows[0]["CM_CHAT_ID"]);
                        tableID = Convert.ToInt32(ds.Tables[0].Rows[0]["AD_TABLE_ID"]);
                        RecordID = Convert.ToInt32(ds.Tables[0].Rows[0]["RECORD_ID"]);
                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => SetData(ds));
                    }
                    else
                    {
                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                        {
                            NoRecords();
                        });
                    }

                }
                else
                {
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {
                        NoRecords();
                    });
                }
            });
        }

        public void NoRecords()
        {
            IsListVisible = Visibility.Collapsed;
            BusyIndicator = false;
            IsTextVisible = Visibility.Visible;
            Records = Msg.GetMsg("NoRecordFound");
        }

        public void SetData(DataSet ds)
        {
            ClearItems();
            ChatText = null;
            IsTextVisible = Visibility.Collapsed; ;
            int count = 0;
            //if (ds.Tables[0].Rows.Count >= 2)
            //{
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                count++;
                AddItems(ds, i);
               
            }
            //}
            //else
            //{
            //    AddItems(ds, 0);
            //}
            BusyIndicator = false;
            /// _isListVisible = Visibility.Visible;
        }

        public void AddItems(DataSet ds, int rowNo)
        {
            MemoryStream ms = null;
            if (ds.Tables[0].Rows[rowNo]["BINARYDATA"] != DBNull.Value)
            {
                ms = new MemoryStream((Byte[])ds.Tables[0].Rows[rowNo]["BINARYDATA"]);
            }
            Add(new LatestSubscribedRecordChat(ms, ds.Tables[0].Rows[rowNo]["CHARACTERDATA"].ToString(), ds.Tables[0].Rows[rowNo]["CREATED"].ToString(), ds.Tables[0].Rows[rowNo]["NAME"].ToString(),  Width - SUBTRACTED_WIDTH));
        }

        public void SaveData()
        {
            if (ChatText != null && ChatText != "")
            {
                BusyIndicator = true;
                _isListVisible = Visibility.Collapsed;
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    //int chatEntryId = DB.GetNextID(Envs.GetCtx().GetAD_Client_ID(), "CM_CHATENTRY", null);
                    //string sql = "insert into cm_chatEntry(ad_client_id, ad_org_id, ad_user_id,CHARACTERDATA, cm_chatentry_id, cm_chat_id, chatentrytype, confidentialtype, createdby, updatedby )"
                    //       + " values(" + Envs.GetCtx().GetAD_Client_ID() + ", " + Envs.GetCtx().GetAD_Org_ID() + ", " + Envs.GetCtx().GetAD_User_ID() + ", '" + ChatText + "', " + chatEntryId + ", "
                    //+ " " + chatId + ", 'N', 'A'," + Envs.GetCtx().GetAD_User_ID() + ", " + Envs.GetCtx().GetAD_User_ID() + ")";
                    //int IsInserted = DB.ExecuteQuery(sql);
                    MChat _chat = new MChat(Envs.GetCtx(), chatId, null);
                    MChatEntry entry = new MChatEntry(_chat, ChatText);
                    if (entry.Save())
                    {

                    }
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => GetData());
                    //  GetData();
                });
            }
        }
        Visibility _isListVisible = new Visibility();
        public Visibility IsListVisible
        {
            get
            {
                return _isListVisible;
            }
            set
            {
                _isListVisible = value;
                OnPropertyChanged("IsListVisible");
            }
        }

        Visibility _isTextVisible = new Visibility();
        public Visibility IsTextVisible
        {
            get
            {
                return _isTextVisible;
            }
            set
            {
                _isTextVisible = value;
                OnPropertyChanged("IsTextVisible");
            }
        }

        bool _busyIndicator = true;
        public bool BusyIndicator
        {
            get
            {
                return _busyIndicator;
            }
            set
            {
                _busyIndicator = value;
                OnPropertyChanged("BusyIndicator");
            }
        }

        public double _width = 0;
        public double Width
        {
            get
            {
                return _width;
            }
            set
            {
                _width = value;
            }
        }


        string _text = null;
        public string ChatText
        {
            get
            {
                return _text;
            }
            set
            {

                _text = value;
                if (_text == null)
                {
                    OnPropertyChanged("ChatText");
                }
            }
        }

        string _records = null;
        public string Records
        {
            get
            {
                return _records;
            }
            set
            {
                _records = value;
                if (_records != null)
                {
                    OnPropertyChanged("Records");
                }
            }
        }

        public void ZoomToRecord()
        {

            VAdvantage.Apps.AWindow win = new VAdvantage.Apps.AWindow();
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                string sql = "select cmsub.ad_window_id,ad.name,ad.name,adt.tablename||'_ID' as TableID FROM cm_subscribe  cmsub join ad_window ad on(ad.ad_window_id= cmsub.ad_window_id) ";
                sql += " join ad_table adt on(adt.ad_table_id= cmsub.ad_table_id) where cmsub.ad_table_id=" + tableID + " and cmsub.record_id=" + RecordID + " AND cmsub.ad_user_id=" + Envs.GetCtx().GetAD_User_ID();
                DataSet ds = new DataSet();
                ds = DB.ExecuteDataset(sql, null);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    int AD_Window_ID = Convert.ToInt32(ds.Tables[0].Rows[0]["AD_WINDOW_ID"]);		// hardcoded
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate
                     {
                         if (AD_Window_ID <= 0)
                         {
                             return;
                         }
                         bool showWin = win.InitWindow(AD_Window_ID, VAdvantage.Classes.Query.GetEqualQuery(ds.Tables[0].Rows[0]["TABLEID"].ToString(), RecordID));//  int.Parse(ctrl.Rows[ctrl.CurrentRow.Index].Cells[primaryKey].Value.ToString())));
                         //this.Cursor = Cursors.Arrow;
                         //if (showWin)
                         //    win.Show();
                     });
                }
            });
        }


        private ICommand _zoom = null;
        public ICommand Zoom
        {
            get
            {
                if (_zoom == null)
                {
                    _zoom = new Buttonclick(ZoomToRecord);
                }
                return _zoom;
            }
            set
            {
                _zoom = value;
            }
        }


        protected void OnPropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }


        private ICommand _buttonClick = null;
        public ICommand ButtonClick
        {

            get
            {
                if (_buttonClick == null)
                {

                    _buttonClick = new Buttonclick(SaveData);
                }
                return _buttonClick;
            }
            set
            {

                _buttonClick = value;
            }
        }


    }


    public class Buttonclick : ICommand
    {
        private Action _a;
        public Buttonclick(Action a)
        {

            _a = a;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            _a.Invoke();
        }
    }
}
